package com.cis467.mrball.backend;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.zip.DataFormatException;

import android.content.res.Resources;

import com.cis467.mrball.HighScore;
import com.cis467.mrball.R;
import com.cis467.mrball.R.raw;
import com.cis467.mrball.parts.Level;
import com.cis467.mrball.parts.LevelWrapper;
import com.cis467.mrball.parts.TestLevel;



public final class GameManagement{	
	
	/*
	 * ********* Player Info ***********
	 */
	public static String get_playerID(){
		return LocalContent.getUserID();

	}
	
	public static void setupGame(Resources resources){
		
		BufferedReader bufferedReader;
		
		LocalContent.createDirectories();
		
		try {
			
			int[] levelKeys = {R.raw.t01_enter, R.raw.t02_walls, R.raw.t03_lasers, R.raw.t04_key, 
							   R.raw.t05_pits, R.raw.t06_slow, R.raw.t07_fast, R.raw.t08_review1, 
							   R.raw.t09_portal, R.raw.t10_2portals, R.raw.t11_4portals, 
							   R.raw.t12_button, R.raw.t13_2buttons, R.raw.t14_buttonnobutton, 
							   R.raw.t15_2button2nobutton, R.raw.t16_blockedportal, 
							   R.raw.t17_review2, R.raw.t18_review3, R.raw.t19_plinko, R.raw.t20_exit};
			
			for(int key : levelKeys) {
			
				// Open the input file
				bufferedReader = 
					new BufferedReader(new InputStreamReader(resources.openRawResource(key)));
				
				char[] buffer = new char[99999];
				
				bufferedReader.read(buffer);
				
				//String levelXML = new String(buffer);
				
				//bufferedReader.read(buffer, 0, buffer.length);
				
				String levelXML = new String(buffer).split("</map>")[0] + "</map>";
				
				Level level = LocalContent.convertXML(levelXML);
				
			//	LocalContent.saveFile(levelXML, LocalContent.corePath, level.getName());
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		OnlineContent.newUser();
	}
	
	// TODO this needs to replace the existing method
	public static void TEMPsetupGame(Resources resources, MrBallSQLiteOpenHelper mSQLiteHelper){
		
		BufferedReader bufferedReader;
		
		try {
			
			int[] levelKeys = {R.raw.t01_enter, R.raw.t02_walls, R.raw.t03_lasers, R.raw.t04_key, 
							   R.raw.t05_pits, R.raw.t06_slow, R.raw.t07_fast, R.raw.t08_review1, 
							   R.raw.t09_portal, R.raw.t10_2portals, R.raw.t11_4portals, 
							   R.raw.t12_button, R.raw.t13_2buttons, R.raw.t14_buttonnobutton, 
							   R.raw.t15_2button2nobutton, R.raw.t16_blockedportal, 
							   R.raw.t17_review2, R.raw.t18_review3, R.raw.t19_plinko, R.raw.t20_exit};
			
			for(int key : levelKeys) {
			
				// Open the input file
				bufferedReader = 
					new BufferedReader(new InputStreamReader(resources.openRawResource(key)));
				
				char[] buffer = new char[99999];
				
				bufferedReader.read(buffer);
				
				//String levelXML = new String(buffer);
				
				//bufferedReader.read(buffer, 0, buffer.length);
				
				String levelXML = new String(buffer).split("</map>")[0] + "</map>";
				
				Level level = LocalContent.convertXML(levelXML);
				
			//	LevelWrapper levelWrapper = new LevelWrapper(level, level.getCreator(), level.getName());
				
			//	mSQLiteHelper.insertLevelFromWrapper(levelWrapper);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		OnlineContent.newUser();
	}
	
	public static boolean nothingSaved() {
		if(get_playerID() == "")
			return true;
		else
			return false;
	}
	
	
	/*
	 *  ********* HS Methods **************
	 */
	/*
	 * handle new high score
	 */
	public static void new_highScore(HighScore new_HighScore){

		//boolean newHighScore = false;
		
		try{
			LocalContent.set_NewHS(new_HighScore);
		//	newHighScore = true;
		}catch (Exception e){
			// not a new high score
			e.printStackTrace();
		}
		//if( newHighScore )
			//OnlineContent.set_HighScore(new_HighScore);

	}
	
	/*
	 * returns the top 10 local high scores for level
	 */
	public static HighScore[] get_myHighScores() throws Exception{
		HighScore[] myHighScores;

		 myHighScores = LocalContent.getHighScores();

		return myHighScores;
	}
	

	/*
	 * returns the the users high scores on the server. May return null.
	 * @return Scores of the user saved on the server, Null if no scores exist.
	 * @throws DataFormatException if content not found or returned incorrectly
	 */
	public static HighScore[] download_myHighScores(){
		// returning null indicates no high scores exist on server.
		return OnlineContent.get_myHighScores();
			
	}

	/*
	 * returns the top 10 high scores globally for the level
	 * @throws DataFormatException if content not found or returned incorrectly
	 */
	public static HighScore[] download_HighScores(Level mbLevel) throws DataFormatException{
		
		HighScore[] retval = null;
	
		try{
			retval = OnlineContent.get_HighScores(mbLevel);		
		}catch(Exception e){
			// check local
		}
		if(retval == null){
			throw new DataFormatException();
		}
		return retval;
	}
	
	
	
	/*
	 * ************* LEVEL METHODS ******************
	 */
	/*
	 * returns a level object from the server based on lvl unique key
	 */
	public static ArrayList<Level> download_Level() throws Exception{	
		return OnlineContent.download_level();
	}
	
	/*
	 * submits a user created level to the Server
	 */
	public static void upload_Level(Level submitLevel){
		 
		     try {
				OnlineContent.upload_Level(submitLevel);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

	}
	
	/*
	 * Throws exception if saving level failed
	 * myLevel - level to save
	 * builder - if from level builder true
	 * else it is from download option
	 */
//	public static void save_Level(Level myLevel, boolean builder ) throws Exception{
//		
//		String path;
//		
//		if (builder)
//			path = LocalContent.builderPath;
//		else
//			path = LocalContent.downloadPath;
//		LocalContent.saveFile(
//							myLevel.toString(), 
//							path,
//							myLevel.getCreator() + "." + myLevel.getName()
//							);		
//	}
	
	
	//currently undefined
	/*
	 * returns 10 level segments based on a user query
	 * this should be used when displaying previews of levels for to download
	 */
	public static Level[] queryLevels(String query){
		Level[] lvlChoices =  new Level[10];
		//OnlineManagement.getLevels(query);
		for (int i = 0; i < lvlChoices.length; i++){
			lvlChoices[i] = new Level();
		}	
		return lvlChoices;
		
	}



	public static Level get_Level(String name, char type ) throws Exception {
		String path = "";
		
		if (type == 'c')
			path = LocalContent.corePath;
		else if (type == 'd')
			path = LocalContent.downloadPath;
		else if (type == 'b')
			path = LocalContent.builderPath;
		else
			path = "";
		
		return LocalContent.get_Level(path+name);

	}

	public static ArrayList<Level> get_playableLevels() throws Exception {
		
		ArrayList<Level> downloaded = LocalContent.get_dlLevels();
		ArrayList<Level> built = LocalContent.get_buildLevels();
		
		if(built.size() > 0)
			downloaded.addAll(built);
		else if(downloaded.size() == 0)
			downloaded.add(new TestLevel().getLevel());
		return downloaded;
	}
	
	public static ArrayList<Level> get_builderLevels() throws Exception {
		return LocalContent.get_buildLevels();
	}

}